<?php
class IndexController extends BaseController
{	
	const LIST_KEY = 'roomlist';
	const LIST_USER='userlist';
	const PREFIX ='gm_';
	public function indexAction()
	{
		$this->success('hello world');
	}
	
	//登录
	public function loginAction()
	{	

		$data = $this->getRequest()->getParams();
		//$member_id=$data['member_id'];
		$fromuser=$data['member_id'];
		if(!$fromuser){
			$this->error('微信标识不存在');
			return;
		}
		$memberTable = new HbModel(self::PREFIX.'member');
		$memberInfo = $memberTable->where(array('fromuser'=>$fromuser))->find();

		$username = $memberInfo['fromuser'];
		$token = $memberInfo['token'];
		$mUser = new UserModel(null, false);
		if(!$mUser->login($username, $token)){
			$nickname =$memberInfo['nickname'];
			$headimgurl=$memberInfo['headimgurl'];
			$response_result = $this->autoRegister($username,$nickname,$headimgurl);
			//注册之后登录
			$res = $mUser->login($response_result['username'],$response_result['token']);
			if(!$res){
				$this->error('InvalidToken');
				return ;
			}			
		}
		
		//关闭原连接
		$uid = $mUser->getUid();
		$oldsid = Socket::getSessionId($uid);
		if($oldsid){
			Socket::close($oldsid);
		}
		
		//绑定socket
		Socket::bind(SESSIONID, $uid);
		
		//获取数据
		$user = $mUser->getInfo();
		//file_put_contents("./controllers/userinfo.txt", 'login_'.json_encode($user).PHP_EOL,FILE_APPEND);
		$this->success($user);
	}
	/**
	 * 注册用户
	 * [autoRegister description]
	 * @return [type] [description]
	 */
	public function autoRegister($fromuser,$nickname,$headimgurl){
		$username =$fromuser;
		$nickname =$nickname?$nickname:$this->randUsername();
		$redis = RedisDB::factory('user');
		$uid = $redis->incr(UserModel::USERID_KEY);
		$ret = $redis->hSetNx(UserModel::USERNAME_KEY, $username, $uid);
		if(!$ret){
			return 'UserNameExists';
		}
		//write user info
		$user = array(
			'uid' => $uid,
			'username' => $username,
			'nickname' => $nickname,
			'point' => 0,
			'gold' => 0,//钻石
			'level'=>0,
			'headimgurl'=>$headimgurl,
			'paiju'=>0,//总局数
			'victory'=>0,//胜利
			'escape'=>0,//逃跑
			'regdate' => time(),
		);
		$redis->hMSet(UserModel::INFO_KEY . $uid, $user);
		$redis->hSetNx(self::LIST_USER,$uid,json_encode($user));

		//write auth info
		$token = md5(date('YmdHis') . mt_rand(1000, 9999) . $username);
		$redis->hSet(UserModel::AUTH_KEY, $username, $token);
		//保存token
		$memberTable = new HbModel(self::PREFIX.'member');
		$sql="UPDATE ".self::PREFIX."member  SET token='".$token."' WHERE fromuser='".$fromuser."'";
		
		$memberTable->execute($sql);
		return array(
				'username'=>$username,
				'token'=>$token,
			);
	}
	private	function randUsername()
	{
		$str = '0123456789abcdefghijklnmopqrstuvwxyz';
		$len = strlen($str);
		$ret = '';
		for($i = 0; $i < 8; ++$i){
			$idx = mt_rand(0, $len - 1);
			$ret.= $str{$idx};
		}
		return $ret;
	}
	//注册(测试用)
	public function registerAction()
	{
		//$data = $this->getRequest()->getParams();
		//$username = trim($data['username']);
		//$nickname = trim($data['nickname']);
		$username ='xiecl';
		$data['username']='xiecl';
		$nickname='小米';
		if(!$username){
			$this->error('InvaludUserName');
			return ;
		}
		if(!$nickname){
			$this->error('InvalidNickName');
			return ;
		}
		
		$redis = RedisDB::factory('user');
		$uid = $redis->incr(UserModel::USERID_KEY);
		$ret = $redis->hSetNx(UserModel::USERNAME_KEY, $username, $uid);
		if(!$ret){
			$this->error('UserNameExists');
			return ;
		}
		
		//write user info
		$user = array(
			'uid' => $uid,
			'username' => $username,
			'nickname' => $nickname,
			'gamepoint' => 0,
			'gold' => 20,
			'regdate' => time(),
		);
		$redis->hMSet(UserModel::INFO_KEY . $uid, $user);
		
		//write auth info
		$token = md5(date('YmdHis') . mt_rand(1000, 9999) . $username);
		$redis->hSet(UserModel::AUTH_KEY, $data['username'], $token);
		
		$this->success(array(
			'username' => $username,//xiecl
			'token' => $token,//d9947f8a06c6cbec47e13548e7cb0c9c
		));
	}
	
	//客户端连接
	public function onConnectAction()
	{
		
		$mUser = new UserModel();
		$uid = $mUser->getUid();
		//file_put_contents("./logs/connect.txt", $uid.PHP_EOL,FILE_APPEND);

	}
	
	//客户端关闭
	public function onCloseAction()
	{
		$mUser = new UserModel();
		$uid = $mUser->getUid();
		$user = $mUser->getInfo();
		file_put_contents("./logs/close.txt", $uid.PHP_EOL,FILE_APPEND);
		$ret = Socket::unbind(SESSIONID, $uid);
		
		//玩家离线处理
		if($ret){
			if(!empty($user['roomid'])){
				$mRoom = new ElephantajiangModel($mUser, $user['roomid']);
				$mRoom->offline($user['seatid'],$user);
				//$mRoom->reconnet();
			}
		}
	}
	
	//创建房间
	public function createAction()
	{
		$mUser = new UserModel();
		$user = $mUser->getInfo();
		if($user['gold'] < 5){
			$this->error('GoldLess');
			return ;
		}
		
		if(!empty($user['roomid'])){
			$this->error('InRoom');
			return ;
		}
		
		$mGame = new RoomModel($mUser);
		$ret = $mGame->create();
		if(!$ret){
			$this->error('CreateFailed');
			return ;
		}
		
		//update user info
		$mUser->save(array(
			'roomid' => $mGame->getId(),
		));
		
		$this->success($ret);
	}
	

	
	
}
